package com.whiteape.book.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.wang.avi.AVLoadingIndicatorView;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.bo.ScrollBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceCategoryBean;
import com.whiteape.book.ui.activity.SiteCategoryDetailActivity;
import com.whiteape.book.ui.adapter.ScrollLeftAdapter;
import com.whiteape.book.ui.adapter.ScrollRightAdapter;
import com.whiteape.book.ui.base.BaseFragment;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.ScreenUtils;
import com.whiteape.book.widget.itemdecoration.DividerItemDecoration;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;

public class SiteCategoryFragment extends BaseFragment {

    @BindView(R.id.rv_left)
    RecyclerView rvLeft;

    @BindView(R.id.rv_right)
    RecyclerView rvRight;

    @BindView(R.id.tv_right_title)
    TextView tvRightTitle;

    @BindView(R.id.category_iv_how)
    ImageView ivHow;

    @BindView(R.id.avi)
    AVLoadingIndicatorView mLoadingAVI;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private Map<SiteSourceBean, Map<String, String>> categoryMap;

    private ScrollLeftAdapter leftAdapter;

    private ScrollRightAdapter rightAdapter;

    //title的高度
    private int tHeight;

    //记录右侧当前可见的第一个item的position
    private int first = 0;

    private List<String> leftData = new ArrayList<>();
    private List<ScrollBean> rightData = new ArrayList<>();

    private GridLayoutManager rightManager;

    //右侧title在数据中所对应的position集合
    private List<Integer> tPosition = new ArrayList<>();

    @Override
    protected int getContentId() {
        return R.layout.fragment_category;
    }


    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (getActivity() == null) {
            return;
        }
        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
            ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("分类浏览");
        }

//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
//        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用

        rightAdapter = new ScrollRightAdapter(R.layout.item_scroll_right, R.layout.layout_right_title, rightData);
        rightManager = new GridLayoutManager(getContext(), 3);
        rvRight.setLayoutManager(rightManager);
        Context context = getContext();
        rvRight.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(ScreenUtils.dpToPx(ScreenUtils.getDimens(context, R.dimen.widget_size_3))
                        , 0
                        , ScreenUtils.dpToPx(ScreenUtils.getDimens(context, R.dimen.widget_size_3))
                        , ScreenUtils.dpToPx(ScreenUtils.getDimens(context, R.dimen.widget_size_3)));
            }
        });
        rvRight.setAdapter(rightAdapter);

//        if (rightData.size() > 0 && rightData.get(first).isHeader) {
//            tvRightTitle.setText(rightData.get(first).header);
//
//        }

        leftAdapter = new ScrollLeftAdapter(R.layout.item_scroll_left, leftData);
        rvLeft.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        rvLeft.addItemDecoration(new DividerItemDecoration(getContext()));
        rvLeft.setAdapter(leftAdapter);


    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initLeftEvent();
        initRightEvent();
        ivHow.setOnClickListener((v -> {
            if (getActivity() == null) {
                return;
            }
            new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.wa_common_tip)
                    .setMessage(R.string.category_how_to)
                    .setPositiveButton(R.string.wa_common_know_it, (dialog, which) -> {
                        dialog.dismiss();
                    }).show();
        }));
    }

    private void initLeftEvent() {
        leftAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    //点击左侧列表的相应item,右侧列表相应的title置顶显示
                    //(最后一组内容若不能填充右侧整个可见页面,则显示到右侧列表的最底端)
                    case R.id.item:
                        leftAdapter.selectItem(position);
                        rightManager.scrollToPositionWithOffset(tPosition.get(position), 0);
                        leftAdapter.notifyDataSetChanged();
                        break;
                }
            }
        });
    }

    private void initRightEvent() {
        rvRight.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //获取右侧title的高度
                tHeight = tvRightTitle.getHeight();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if(rightData.isEmpty()) {
                    return;
                }
                //判断如果是header
                if (rightData.get(first).isHeader) {
                    //获取此组名item的view
                    View view = rightManager.findViewByPosition(first);
                    if (view != null) {
                        //如果此组名item顶部和父容器顶部距离大于等于title的高度,则设置偏移量
                        if (view.getTop() >= tHeight) {
                            tvRightTitle.setY(view.getTop() - tHeight);
                        } else {
                            //否则不设置
                            tvRightTitle.setY(0);
                        }
                    }
                }

                //因为每次滑动之后,右侧列表中可见的第一个item的position肯定会改变,并且右侧列表中可见的第一个item的position变换了之后,
                //才有可能改变右侧title的值,所以这个方法内的逻辑在右侧可见的第一个item的position改变之后一定会执行
                int firstPosition = rightManager.findFirstVisibleItemPosition();
                if (first != firstPosition && firstPosition >= 0) {
                    //给first赋值
                    first = firstPosition;
                    //不设置Y轴的偏移量

                    tvRightTitle.setY(0);

                    //判断如果右侧可见的第一个item是否是header,设置相应的值
                    if (rightData.get(first).isHeader) {
                        tvRightTitle.setText(rightData.get(first).header);
                    } else {
                        tvRightTitle.setText(rightData.get(first).t.getType());
                    }
                }

                //遍历左边列表,列表对应的内容等于右边的title,则设置左侧对应item高亮
                for (int i = 0; i < leftData.size(); i++) {
                    if (leftData.get(i).equals(tvRightTitle.getText().toString())) {
                        leftAdapter.selectItem(i);
                        leftAdapter.notifyDataSetChanged();
                        break;
                    }
                }

//                //如果右边最后一个完全显示的item的position,等于bean中最后一条数据的position(也就是右侧列表拉到底了),
//                //则设置左侧列表最后一条item高亮
                if (rightManager.findLastCompletelyVisibleItemPosition() == rightData.size() - 1) {
                    leftAdapter.selectItem(leftData.size() - 1);
                    leftAdapter.notifyDataSetChanged();
                }
            }
        });

        rightAdapter.setOnItemClickListener(((adapter, view, position) -> {
            if (rightData.get(position).isHeader || getContext() == null) {
                return;
            }

            getContext().startActivity(new Intent(getContext(), SiteCategoryDetailActivity.class)
//                    .putExtra(SiteCategoryDetailActivity.KEY_SITE_SOURCE_BEAN, rightData.get(position).t.getSiteSourceBean())
                            .putExtra(SiteCategoryDetailActivity.KEY_SITE_HOST, rightData.get(position).t.getSiteSourceBean().getSiteHostUrl())
                            .putExtra(SiteCategoryDetailActivity.KEY_CATEGORY, rightData.get(position).t.getCategoryBean())
                            .putExtra(SiteCategoryDetailActivity.KEY_CATEGORY_NAME, rightData.get(position).t.getText())
                            .putExtra(SiteCategoryDetailActivity.KEY_CATEGORY_DETAIL_URL, rightData.get(position).t.getUrl())
            );


        }));
    }

    private void updateData(Map<SiteSourceBean, List<SiteSourceCategoryBean>> data) {
        //data的map只有一个entry
        if (data == null || data.isEmpty()) {
            return;
        }
        for (Map.Entry<SiteSourceBean, List<SiteSourceCategoryBean>> entry : data.entrySet()) {

            leftData.add(entry.getKey().getSiteName());
            rightData.add(new ScrollBean(true, entry.getKey().getSiteName()));
            for (SiteSourceCategoryBean bean : entry.getValue()) {
                rightData.add(new ScrollBean(new ScrollBean.ScrollItemBean(entry.getKey().getSiteName(), bean, entry.getKey())));
            }
        }

        if (rightData.size() > 0 && rightData.get(first).isHeader) {
            tvRightTitle.setText(rightData.get(first).header);

        }
        tPosition.clear();
        for (int i = 0; i < rightData.size(); i++) {
            if (rightData.get(i).isHeader) {
                //遍历右侧列表,判断如果是header,则将此header在右侧列表中所在的position添加到集合中
                tPosition.add(i);
            }
        }

        leftAdapter.notifyDataSetChanged();
        rightAdapter.notifyDataSetChanged();
//        mLoadingAVI.hide();

    }

    @Override
    protected void startLogic() {
        super.startLogic();

        //读取本地
        addDisposable(MediaStorageManager.getInstance().getSiteCategoryMap()
                .compose(RxUtils::toSimpleSingle)
                .subscribe(siteSourceBeanListMap -> {
                    updateData(siteSourceBeanListMap);
                    Set<String> siteSourceBeanSet = new HashSet<>();
                    for (Map.Entry<SiteSourceBean, List<SiteSourceCategoryBean>> entry : siteSourceBeanListMap.entrySet()) {
                        siteSourceBeanSet.add(entry.getKey().getSiteHostUrl());
                    }
                    if (siteSourceBeanSet.size() > 0) {
                        mLoadingAVI.hide();
                    } else {
                        mLoadingAVI.show();
                    }
                    //加载本地没有的
                    addDisposable(WebMediaManager.getInstance().getSourceCategoryIndex(siteSourceBeanSet)
                            .compose(RxUtils::toSimpleSingle)
                            .subscribe(siteSourceBeanListMap1 -> {
                                updateData(siteSourceBeanListMap1);
                                for (Map.Entry<SiteSourceBean, List<SiteSourceCategoryBean>> entry : siteSourceBeanListMap1.entrySet()) {
                                    MediaStorageManager.getInstance().saveSiteCategory(entry.getValue());

                                    RxBus.get().post(RxEvent.SITE_SOURCE_CATEGORY_INDEX_ADDED, entry.getKey().getSiteHostUrl());
                                }

                                mLoadingAVI.hide();
                            }, throwable -> {
                                throwable.printStackTrace();
                                mLoadingAVI.hide();
                            }, () -> mLoadingAVI.hide()));

                }, Throwable::printStackTrace)
        );


//        categoryMap = WebMediaManager.getInstance().getSourceCategoryIndex();
//        for (Map.Entry<SiteSourceBean, Map<String, String>> entry : categoryMap.entrySet()) {
//            leftData.add(entry.getKey().getSiteName());
//            rightData.add(new ScrollBean(true, entry.getKey().getSiteName()));
//            for (Map.Entry<String, String> entry1 : entry.getValue().entrySet()) {
//                rightData.add(new ScrollBean(new ScrollBean.ScrollItemBean(entry1.getKey(), entry.getKey().getSiteName(), entry1.getValue(), entry.getKey())));
//
//            }
//        }
//        if (rightData.size() > 0 && rightData.get(first).isHeader) {
//            tvRightTitle.setText(rightData.get(first).header);
//
//        }
//        for (int i = 0; i < rightData.size(); i++) {
//            if (rightData.get(i).isHeader) {
//                //遍历右侧列表,判断如果是header,则将此header在右侧列表中所在的position添加到集合中
//                tPosition.add(i);
//            }
//        }
//
//        leftAdapter.notifyDataSetChanged();
//        rightAdapter.notifyDataSetChanged();

    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.SITE_SOURCE_ADDED),
                    @Tag(RxEvent.SITE_SOURCE_DELETED)
            })
    public void onCollectionStateChanged(Object object) {
//        mPresenter.refreshCollectionMedia(mediaType);
        System.out.println("xxxxxxxxx");
        leftData.clear();
        rightData.clear();
        tPosition.clear();
        tvRightTitle.setText("");
        first = 0;
        leftAdapter.notifyDataSetChanged();
        rightAdapter.notifyDataSetChanged();

        startLogic();
    }
}
